package com.npy.reggie.contorller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.npy.reggie.config.CustomException;
import com.npy.reggie.doman.Category;
import com.npy.reggie.doman.Dish;
import com.npy.reggie.doman.R;
import com.npy.reggie.doman.Setmeal;
import com.npy.reggie.dto.DishDto;
import com.npy.reggie.service.CategoryService;
import com.npy.reggie.service.DishService;
import com.npy.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    DishService dishService;
    @Autowired
    SetmealService setmealService;

    @PostMapping
    public R<String> add(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");

    }

    @GetMapping("/page")
    public R<Page<Category>> page(int page ,int pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);

        QueryWrapper<Category> qw = new QueryWrapper<>();

        qw.lambda().orderByAsc(Category::getSort);

        categoryService.page(pageInfo,qw);
        return R.success(categoryService.page(pageInfo,qw));
    }

    @PutMapping
    public R<String> upDate(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    @DeleteMapping
    public R<String> delete(long id){
        log.info("deleteId{}",id);
        //categoryService.deleteById(id);
        QueryWrapper<Dish> dqw = new QueryWrapper<>();
        //String sid = Long.toString(id);
        dqw.lambda().eq(Dish::getCategoryId,id);
        int count1 = dishService.count(dqw);
        if (count1>0){
            throw new CustomException("分类中包含菜品");
        }
        QueryWrapper<Setmeal> sqw = new QueryWrapper<>();

        sqw.lambda().eq(Setmeal::getCategoryId,id);
        int count = setmealService.count(sqw);
        if (count>0){
            throw new CustomException("分类中包含套餐");
        }

        categoryService.removeById(id);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List<Category>> listR (@RequestParam(required=false,defaultValue = "-1") int type){

        QueryWrapper<Category> qw = new QueryWrapper<>();

        log.info("type:-------{}",type);

        qw.lambda().eq(type!=-1,Category::getType , type);

        List<Category> list = categoryService.list(qw);

        return R.success(list);
    }


}
